package com.ruoyi.store.service.impl;


import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.stage.domain.StuStage;
import com.ruoyi.stage.mapper.StuStageMapper;
import com.ruoyi.store.domain.*;
import com.ruoyi.store.mapper.*;
import com.ruoyi.store.service.IStuPaperService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class StuPaperImpl implements IStuPaperService {
    @Resource
    private StuPaperMapper stuPaperMapper;
    @Resource
    private StuQuestionMapper stuQuestionMapper;
    @Resource
    private StuPaperQuesMapper stuPaperQuesMapper;
    @Resource
    private StuQuesAnwMapper stuQuesAnwMapper;
    @Resource
    private StuUserAnswerMapper stuUserAnswerMapper;
    @Resource
    private StuExamDetailMapper stuExamDetailMapper;
    @Resource
    private StuStageMapper stuStageMapper;
    @Resource
    private RedisCache redisCache;



    @Override
    //查询试卷列表
    public List<StuPaper> selectStuPaperList(StuPaper stuPaper) {
        return stuPaperMapper.selectStuPaperList(stuPaper);
    }

    @Override
    //根据试卷Id查询试卷信息
    public StuPaper selectStuPaperByPaperId(Long paperId) {
        return stuPaperMapper.selectStuPaperByPaperId(paperId);
    }

    /**生成试卷*/
    @Override
    @Transactional
    public int insertPaper(StuPaper stuPaper) {
        Long storeId = stuPaper.getStoreId();
        StuStage stuStage = stuStageMapper.selectStageByStoreId(storeId);
        stuPaper.setStageName(stuStage.getStageName());
        stuPaperMapper.insertPaper(stuPaper);
//        stuPaperMapper.insertPaper(stuPaper);
        //1.先随机从题库根据不同类型抽取题目
        //1.1根据前段传过来的题库id查询题库的所有题目

        List<StuQuestion> storeques = stuQuestionMapper.selectQuesByStoreId(storeId);
        //2.放入试卷中的题目集合
        List<StuQuestion> paperQues = new ArrayList<>();
        //3.随机抽取题目
        int size = storeques.size();
        if (stuPaper.getSingleCount() > size){
          return -1;
        }
        Random random = new Random();
        for (int i = 0; i < stuPaper.getSingleCount(); i++) {
            //每次从题库中随机抽取一道题目
            int myRand = random.nextInt(storeques.size());
            //将抽取的题目添加到试卷题目中去
            paperQues.add(storeques.get(myRand));
            //移除所选题目
            storeques.remove(myRand);
        }
        //4.插入数据库
        int totalMark = 0;
        for(StuQuestion stuQuestion: paperQues){
            StuPaperQues stuPaperQues = new StuPaperQues();
            StuQuesAnwser stuQuesAnwser = stuQuesAnwMapper.selectAnwSerById(stuQuestion.getQuesId());
            stuPaperQues.setPaperId(stuPaper.getPaperId());
            stuPaperQues.setQuesId(stuQuestion.getQuesId());
            stuPaperQues.setQuesType(stuQuestion.getQuesType());
            if (stuPaperQues.getQuesType().equals("单选题")){
                stuPaperQues.setScore(2);
                stuPaperQues.setAnswer(stuQuesAnwser.getAnwser());
            }else if (stuPaperQues.getQuesType().equals("多选题")){
                stuPaperQues.setAnswer(stuQuesAnwser.getManyAnswer());
                stuPaperQues.setScore(4);
            }else if (stuPaperQues.getQuesType().equals("判断题")){
                stuPaperQues.setScore(2);
                stuPaperQues.setAnswer(stuQuesAnwser.getAnwser());
            }else if (stuPaperQues.getQuesType().equals("简答题")){
                stuPaperQues.setScore(10);
            }
            totalMark += stuPaperQues.getScore();
            stuPaperQuesMapper.insertPaperQues(stuPaperQues);
        }
        stuPaper.setTotalMark(totalMark);
        int passMark =  (int)(totalMark * 0.6) ;
        stuPaper.setPassMark(passMark);


        //5.插入试卷信息表的相关数据
        return  stuPaperMapper.updateTotal(totalMark,passMark,stuPaper.getPaperId());
    }

    @Override
    //根据试卷id查询试卷题目信息
    public List<StuPaperQues> selectStuPaperQuesByPaperList(Long paperId) {
        String  key= "stuPaperQues:paper:"+paperId;

        List<StuPaperQues> paperQuesString = redisCache.getCacheList(key);
        //判断试卷不为空,如果有值直接返回Redis中的值
        if (!paperQuesString.isEmpty()){
            return paperQuesString;
        }

        List<StuPaperQues> paperQues = stuPaperQuesMapper.selectStuPaperQuesByPaperList(paperId);
        StuPaper stuPaper = stuPaperMapper.selectStuPaperByPaperId(paperId);
        for (StuPaperQues stuPaperQues: paperQues){
            //循环取出试卷中每道题的quesId,
            Long quesId = stuPaperQues.getQuesId();
            //根据quesId查出题目的名称
            StuQuestion stuQuestion = stuQuestionMapper.selectQuesById(quesId);
            //给paperQues赋值
            stuPaperQues.setQuesName(stuQuestion.getQuesName());
            //根据quesid获取题目的选项
            StuQuesAnwser stuQuesAnwser = stuQuesAnwMapper.selectAnwSerById(quesId);
            //赋值
            stuPaperQues.setSel_ContA(stuQuesAnwser.getSelContA());
            stuPaperQues.setSel_ContB(stuQuesAnwser.getSelContB());
            stuPaperQues.setSel_ContC(stuQuesAnwser.getSelContC());
            stuPaperQues.setSel_ContD(stuQuesAnwser.getSelContD());
            //添加考试的时间
            stuPaperQues.setTotalTime(stuPaper.getTotalTime());
        }

//        如果没有则将数据存到Redis中去
        redisCache.setCacheList(key,paperQues);



        return paperQues;
    }

    @Override
    @Transactional
    //提交试卷并自动对客观题进行评分
    public int insertHisExam(StuHisExam stuHisExam) {
        Long userId = stuHisExam.getUserId();
        Long paperId = stuHisExam.getPaperId();
        //获取试卷所属阶段
        StuPaper stuPaper = stuPaperMapper.selectStuPaperByPaperId(paperId);
        Long storeId = stuPaper.getStoreId();
        StuStage stuStage = stuStageMapper.selectStageByStoreId(storeId);
        String stageName = stuStage.getStageName();


        StuExamDetail stuExamDetail = new StuExamDetail();
        String paperName = stuPaper.getPaperName();
        String isMark = stuExamDetail.getIsMark(); //是否需要阅卷
        isMark = "否";
        stuExamDetail.setPaperId(paperId);
        stuExamDetail.setUserId(userId);
        stuExamDetail.setCreateBy(stuHisExam.getCreateBy());
        stuExamDetail.setPaperName(paperName);
        stuExamDetail.setStageName(stageName);

        long objScore = 0; //客观题
        long answerScore = 0; //主观题


        //生成历史试卷
        List<StuUserAnswer> optionList = stuHisExam.getOptionList();
        for (StuUserAnswer stuUserAnswer:optionList){
            StuQuesAnwser stuQuesAnwser = stuQuesAnwMapper.selectAnwSerById(stuUserAnswer.getQuesId());
            if (stuUserAnswer.getQuesType().equals("多选题")){
                String manyAnswer = stuQuesAnwser.getManyAnswer();
                String userAnswer = stuUserAnswer.getUserAnswer();
                //判分
                markExamPapers(userAnswer,manyAnswer);
                stuUserAnswer.setTrueAnswer(manyAnswer);
                objScore += markExamPapers(manyAnswer, userAnswer);

            }else if (stuUserAnswer.getQuesType().equals("简答题")){
                stuUserAnswer.setTrueAnswer("");
                isMark = "是";

            }else if (stuUserAnswer.getQuesType().equals("单选题") || stuUserAnswer.getQuesType().equals("判断题")){
                String trueAnwser = stuQuesAnwser.getAnwser();
                stuUserAnswer.setTrueAnswer(trueAnwser);
                if (trueAnwser.equals(stuUserAnswer.getUserAnswer())){
                    objScore += 2;
                }
            }
            stuUserAnswer.setUserId(userId);
            stuUserAnswer.setPaperId(paperId);
            stuUserAnswerMapper.insertStuExamHistory(stuUserAnswer);
        }

        stuExamDetail.setIsMark(isMark);
        stuExamDetail.setObjScore(objScore);
        stuExamDetail.setAnswerScore(answerScore);
        //如果没有简答题则设置总分
        if (isMark.equals("否")){
            stuExamDetail.setTotalScore(objScore);
        }

        stuExamDetail.setStatus("已完成");

        stuExamDetailMapper.insertStuExamDetail(stuExamDetail);

        return  1;
    }

    @Override
    @Transactional
    public int delStuPapersByIds(Long[] paperIds) {
        stuPaperMapper.delStuPapersByIds(paperIds);
        stuPaperQuesMapper.delStuPaperQuesByPaperIds(paperIds);
        return 1;
    }

    @Override
    public String checkPaperNameUnique(StuPaper stuPaper) {
        Long PaperId = StringUtils.isNull(stuPaper.getPaperId()) ? -1L : stuPaper.getPaperId();
        StuPaper info = stuPaperMapper.checkStageNameUnique(stuPaper.getPaperName());
        if (StringUtils.isNotNull(info) && info.getPaperId().longValue() != PaperId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    //给多选判分，完全正确4分，全错0分,其余2分
    private long markExamPapers(String manyAnswer, String trueAnswer) {
        long objScore = 0;
        char[] chars = manyAnswer.toCharArray();
        char[] chars1 = trueAnswer.toCharArray();
        //先排序,判断答案是否相等
        Arrays.sort(chars);
        Arrays.sort(chars1);
        boolean equals = Arrays.equals(chars, chars1);
        //如果完全相等，则返回4分
        if (equals){
            return 4;
        }
        //a,b,c
        //a,c
        //如果不完全相等，则两分
        for (char c : chars1) {
            for (char aChar : chars) {
                if (aChar != c) {
                    return  0;
                }else {
                    objScore = 2;
                }
            }
        }

        return  objScore;

    }

    public static void main(String[] args) {
        char[] a = {'a','b','c'};
        char[] b = {'c','g','a'};
        boolean equals = Arrays.equals(a, b);
        System.out.println("hhh");
        System.out.println(equals);
        Arrays.sort(b);
        boolean equals1 = Arrays.equals(a, b);
        if (equals1){
            System.out.println("11111");
        }else {
            System.out.println("2222");
        }

        System.out.println(equals1);
        for (char aa: b){
            System.out.println(aa);
        }
    }



}
